package jdt.geom;

import jdt.utils.JdtUtil;

public class Point {

	/* --- Data members --- */

	/** X coordinate */
	protected double x;

	/** Y coordinate */
	protected double y;

	/* --- Ctors. --- */

	/**
	 * Construct a point using X and Y coordinates
	 * 
	 * @param x
	 *            the X coordinate of the point
	 * @param y
	 *            the Y coordinate of the point
	 */
	public Point(double x, double y) {
		this.x = x;
		this.y = y;
	}

	/* --- Access Methods --- */

	/**
	 * @return x coordinate of this point
	 */
	public double getX() {
		return x;
	}

	/**
	 * @return y coordinate of this point
	 */
	public double getY() {
		return y;
	}

	/* --- Public Methods --- */

	/**
	 * Check if this point is collinear with the argument points
	 * 
	 * @param p1
	 *            a {@link Point}
	 * @param p2
	 *            another {@link Point}
	 * @return
	 */
	public boolean isCollinear(Point p1, Point p2) {
		if (p1.equals(p2)) {
			return true;
		} else {
			double det = JdtUtil.det(p1.x - p2.x, p1.y - p2.y, x - p2.x, y
					- p2.y);
			return Math.abs(det) <= JdtUtil.PERCISION;

		}
	}

	/**
	 * Calculates the distance between this point the the argument point
	 * 
	 * @param p
	 *            The point to find the distance from
	 * @return the calculated distance
	 */
	public double distance(Point p) {
		return Math.sqrt((Math.pow(x - p.x, 2)) + (Math.pow(y - p.y, 2)));
	}

	@Override
	public String toString() {
		return "(" + x + "," + y + ")";
	}

	/* --- Equals and HashCode --- */

	/**
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		long temp;
		temp = Double.doubleToLongBits(x);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		temp = Double.doubleToLongBits(y);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	/**
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof Point)) {
			return false;
		}
		Point other = (Point) obj;
		
		if(distance(other) <= JdtUtil.PERCISION){
			return true;
		}
		
		if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x)) {
			return false;
		}
		if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) {
			return false;
		}
		return true;
	}

	/**
	 * Calculate the dot product of the argument points.
	 * 
	 * @param p1
	 *            The first point
	 * @param p2
	 *            The second point
	 * @return the product
	 */
	public static double dot(Point p1, Point p2) {
		return p1.getX() * p2.getX() + p1.getY() * p2.getY();
	}

}
